package org.yunxin.id;

import com.github.yitter.contract.IdGeneratorOptions;
import com.github.yitter.idgen.YitIdHelper;

import java.math.BigDecimal;
import java.util.Objects;

public class SequenceId {

    private static int workerId = -1;

    private final static SequenceId sequenceId = new SequenceId();

    private SequenceId() {

    }

    /**
     * 分配机器id
     * @param workerId 机器id  取值范围[0,64]
     * @return SequenceId
     */
    public static SequenceId getInstance(int workerId) {
        if (!Objects.equals(SequenceId.workerId, workerId)) {
            init(BigDecimal.valueOf(workerId).shortValue());
            SequenceId.workerId = workerId;
        }
        return sequenceId;
    }

    /**
     * 初始化
     * @param workerId int 最大 workerId [0,64]
     */
    private static void init(short workerId) {
        IdGeneratorOptions options = new IdGeneratorOptions(workerId);
        options.BaseTime = 1735689600000L; // 如果要兼容老系统的雪花算法，此处应设置为老系统的BaseTime。
        options.WorkerIdBitLength = 6; // 默认值6，限定 WorkerId 最大值为2^6-1，即默认最多支持64个节点。
        options.SeqBitLength = 10; // 默认值6，限制每毫秒生成的ID个数。若生成速度超过5万个/秒，建议加大 SeqBitLength }

    }

    public long sequence() {
        return YitIdHelper.nextId();
    }


}
